﻿Imports System.IO
Imports System.Configuration
Imports System.Xml
Imports System.Data.OracleClient

Structure xmlNodes
    Dim custcode As String
    Dim custkey As String
    Dim selldate As String
    Dim serialno As String
    Dim model As String
    Dim eucell As String
    Dim euname As String
    Dim euadd As String
    Dim resptime As String
End Structure
Public Class sms_frmMain
    Private Sub notifyIcon1_DoubleClick(Sender As Object, e As EventArgs) Handles notifyIcon1.DoubleClick
        ' Show the form when the user double clicks on the notify icon. 
        Me.Opacity = 100
        Me.Show()
        Me.WindowState = FormWindowState.Normal

    End Sub
    Private Sub menuItem1_Click(Sender As Object, e As EventArgs) Handles menuItem1.Click
        ' Close the form, which closes the application.
        Me.Close()
    End Sub
    Private Sub sms_frmMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        If MsgBox("Are you really sure to quit?", vbCritical + vbYesNo) = vbYes Then
            Call oradbClose()
            Call saveLogs()
            notifyIcon1.Dispose()

            End
        Else
            e.Cancel = True
        End If
    End Sub
    Private Sub sms_frmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
        'gMoTmr.Interval = smsSettings.mo_tmrInt
        'sMtTmr.Interval = smsSettings.mt_tmrInt
        rMCTmr.Interval = smsSettings.mc_tmrInt

        'gMoTmr.Enabled = True
        'sMtTmr.Enabled = True
        rMCTmr.Enabled = True

    End Sub
    Private Sub gMoTmr_Tick(sender As Object, e As EventArgs) Handles gMoTmr.Tick
        Dim _modir As String = _smsRootdir + smsSettings.modir
        _modir = mkDir(_modir)

        'read xml file list on MO directory
        xmlNodebyXmlFiles(_modir)

    End Sub
    Private Sub rMCTmr_Tick(sender As Object, e As EventArgs) Handles rMCTmr.Tick
        Dim _mcdir As String = _smsRootdir + smsSettings.mcdir
        _mcdir = mkDir(_mcdir)

        xmlNodesbyXmlFiles(_mcdir)
    End Sub
    Private Sub sMtTmr_Tick(sender As Object, e As EventArgs) Handles sMtTmr.Tick
        Call swSend()

        Dim _isnextday As String = Format(Date.Now, "yyyyMMdd")
        If Val(_isnextday) > Val(_today) Then
            Call saveLogs()
            _today = _isnextday
        End If
    End Sub
    Private Sub sms_frmMain_Resize(sender As Object, e As EventArgs) Handles Me.Resize
        If Me.WindowState = FormWindowState.Minimized Then
            Me.Opacity = 0
            Me.Hide()
        End If
    End Sub
#Region "#_PRIVATE SUBs & FUNs"
    Private Sub xmlNodebyXmlFiles(ByVal directory As String, Optional ByVal extension As String = "*.xml")
        Dim dir As DirectoryInfo = New DirectoryInfo(directory)
        Dim lstOfFile As FileInfo() = dir.GetFiles(extension)

        Try
            For Each fi As FileInfo In lstOfFile
                Dim _fullfilename As String = fi.FullName
                Dim _filename As String = fi.Name

                readXmlNode(_fullfilename, _filename)
            Next
        Catch ex As Exception
            rtbLog.AppendText(vbNewLine + ex.Message)
        End Try
    End Sub
    Private Sub xmlNodesbyXmlFiles(ByVal directory As String, Optional ByVal extension As String = "*.xml")
        Dim dir As DirectoryInfo = New DirectoryInfo(directory)
        Dim lstOfFile As FileInfo() = dir.GetFiles(extension)

        'Try
        For Each fi As FileInfo In lstOfFile
            Dim _fullfilename As String = fi.FullName
            Dim _filename As String = fi.Name

            readXmlNodes(_fullfilename, _filename)
        Next
        'Catch ex As Exception
        '    rtbLog.AppendText(vbNewLine + ex.Message)
        'End Try
    End Sub
    Private Sub readXmlNode(ByVal fullfilename As String, ByVal filename As String)
        Dim cell_no As String
        Dim shortcode As String
        Dim moseq As String
        Dim cmdcode As String
        Dim msgbody As String
        Dim msgreceive_time As String
        Dim filedatetime As String

        Application.DoEvents()
        Try
            If rtbLog.Text.Trim = "" Then
                rtbLog.AppendText("Reading..." + fullfilename)
            Else
                rtbLog.AppendText(vbNewLine + "<==================================================================>")
                rtbLog.AppendText(vbNewLine + "Reading..." + fullfilename)
            End If

            Dim _doc As New XmlDocument
            _doc.Load(fullfilename)
            Dim nodelist As XmlNodeList

            'Read node values
            nodelist = _doc.GetElementsByTagName("msisdn")
            cell_no = nodelist(0).InnerText.Trim
            nodelist = _doc.GetElementsByTagName("shortcode")
            shortcode = nodelist(0).InnerText.Trim
            nodelist = _doc.GetElementsByTagName("cmdcode")
            cmdcode = nodelist(0).InnerText.Trim
            nodelist = _doc.GetElementsByTagName("msgbody")
            msgbody = nodelist(0).InnerText.Trim
            nodelist = _doc.GetElementsByTagName("moseq")
            moseq = nodelist(0).InnerText.Trim
            nodelist = _doc.GetElementsByTagName("sReqTime")
            msgreceive_time = nodelist(0).InnerText.Trim
            filedatetime = filename.Substring(0, InStr(filename, "_", CompareMethod.Text) - 1).Trim

            'Insert to MO table
            Dim sql As String = "pk_sms_mst.pr_update_mo_hist('" + cell_no + "','" +
                                                                   shortcode + "','" +
                                                                   moseq + "','" +
                                                                   cmdcode + "','" +
                                                                   msgbody + "','" +
                                                                   msgreceive_time + "','" +
                                                                   fullfilename.ToUpper + "','" +
                                                                   filedatetime.ToUpper + "')"

            Dim sqlcmd As OracleCommand = New OracleCommand(sql, oradbConnection)
            sqlcmd.CommandType = CommandType.StoredProcedure
            sqlcmd.ExecuteNonQuery()

            rtbLog.AppendText("...done, " + Format(Date.Now, "yyyyMMdd HH:mm:ss"))
            Application.DoEvents()
            rtbLog.AppendText(vbNewLine + "Backing up..." + filename)

            'Making backup for MO file
            Dim _bkdir As String = _smsRootdir + smsSettings.mcbkdir
            _bkdir = mkDir(_bkdir)
            Dim _todaybkdir As String = _bkdir + Format(Date.Today, "yyyyMMdd")
            _todaybkdir = mkDir(_todaybkdir)
            IO.File.Copy(fullfilename, _todaybkdir + filename, True)
            IO.File.Delete(fullfilename)

            rtbLog.AppendText("...done, " + Format(Date.Now, "yyyyMMdd HH:mm:ss"))

        Catch ex As Exception
            rtbLog.AppendText("<==================================================================>")
            rtbLog.AppendText(ex.Message + ", " + Format(Date.Now, "yyyyMMdd HH:mm:ss"))
        End Try
    End Sub
    Private Sub readXmlNodes(ByVal fullfilename As String, ByVal filename As String)

        'Starting to read the xml file
        Dim cHeader As String = filename.Substring(1, InStr(filename, "_").ToString.Length - 1)
        Dim _doc As XDocument = XDocument.Load(fullfilename)

        'Dim nodelist As XmlNodeList
        Dim XmlNode As New xmlNodes

        Dim xnList = From i In _doc.Element("PRODUCT").Elements("LG")
                     Select cust_code = i.Element("cid").Value, cust_key = i.Element("cust_key").Value, _
                            sell_date = i.Element("sell_date").Value, serial_no = i.Element("serial_no").Value, _
                            model = i.Element("model").Value, eucell = i.Element("cust_phone").Value, _
                            euname = i.Element("cust_name").Value, euadd = i.Element("cust_add").Value, _
                            resptime = i.Element("sReqTime").Value

        rtbLog.AppendText(vbNewLine + "=======MC_EDI IS BEING PROCESS FOR " + cHeader + "@" + Format(Date.Now, "yyyyMMdd HH:mm:ss") + "===========")
        For Each xn In xnList
            With XmlNode
                .custcode = xn.cust_code.ToString
                .custkey = xn.cust_key.ToString
                .selldate = xn.sell_date.ToString
                .serialno = xn.serial_no.ToString
                .model = xn.model.ToString
                .eucell = xn.eucell.ToString
                .euname = xn.euname.ToString
                .euadd = xn.euadd.ToString
                .resptime = xn.resptime
                Dim sqlcmd As String = "pk_edi_mst.pr_update_cust_upload ('" + .custcode + "'" +
                                                                         ",'" + .custkey + "'" +
                                                                         ",'" + .serialno + "'" +
                                                                         ",'" + .model + "'" +
                                                                         ",'" + .selldate + "'" +
                                                                         ",'" + .eucell + "'" +
                                                                         ",'" + .euname + "'" +
                                                                         ",'" + .euadd + "'" +
                                                                         ",'" + .resptime + "')"

                Dim sqlexecmd As OracleCommand = New OracleCommand(sqlcmd, oradbConnection)
                sqlexecmd.CommandType = CommandType.StoredProcedure
                sqlexecmd.ExecuteNonQuery()
                'Dispose the current session
                For Each param In sqlexecmd.Parameters
                    param.dispose()
                Next
                sqlexecmd.Dispose()
                sqlexecmd = Nothing

                rtbLog.AppendText(vbNewLine + .custcode + "/" + .custkey + "/" + .serialno + "/" + .model + "/" + .selldate + "/" + .euname + "/" + .eucell + "/" + .euadd + "/" + .resptime)

            End With
        Next

        rtbLog.AppendText(vbNewLine + "======================MC EDI IS DONE======================")

        'Do backup for readed file
        Dim _bkdir As String = _smsRootdir + smsSettings.mcbkdir
        _bkdir = mkDir(_bkdir)
        Dim _todaybkdir As String = _bkdir + Format(Date.Today, "yyyyMMdd")
        _todaybkdir = mkDir(_todaybkdir)
        IO.File.Copy(fullfilename, _todaybkdir + filename, True)
        IO.File.Delete(fullfilename)
    End Sub
    Private Sub swSend()
        Try
            Dim _url As String = smsSettings.ws_url
            Dim ws As wsSendMT.Service = New wsSendMT.Service()
            ws.Url = _url

            Dim sql As String = " SELECT   moseq " +
                                         ",shortcode " +
                                         ",cell_no " +
                                         ",msgbody " +
                                         ",msgtype " +
                                         ",mttotalseq " +
                                         ",mtseqref " +
                                         ",cpid" +
                                " FROM  tb_mt_hist " +
                                " WHERE send_flag  ='N'"
            Dim sqlcmd As OracleCommand = New OracleCommand(sql, oradbConnection)
            Dim _dataAdapter As OracleDataAdapter = New OracleDataAdapter
            _dataAdapter.SelectCommand = sqlcmd
            Dim _dataTable As New DataTable

            _dataAdapter.Fill(_dataTable)

            For Each _row As DataRow In _dataTable.Rows
                Application.DoEvents()

                Dim _mt_send_datetime = Format(Date.Now, "MMddyyyyHHmmss")

                rtbLog.AppendText(vbNewLine + "<===========================================================================>")
                rtbLog.AppendText(vbNewLine + "MT started : " + Format(Date.Now, "yyyy/MM/dd HH:mm:ss") + " to " + _row("cell_no").ToString)

                Dim _result As Integer = ws.SendMT(_row("moseq").ToString, _
                                                   _row("shortcode").ToString, _
                                                   _row("cell_no").ToString, _
                                                   _row("msgbody").ToString, _
                                                   _row("msgtype").ToString, _
                                                   _row("mttotalseq").ToString,
                                                   _row("mtseqref").ToString, _
                                                   _row("cpid").ToString, _
                                                   "1", _
                                                   smsSettings.ws_user, _
                                                   smsSettings.ws_pwd)

                Dim _mt_sent_datetime = Format(Date.Now, "MMddyyyyHHmmss")
                If _result = 200 Then
                    sql = " UPDATE tb_mt_hist SET send_flag   ='Y', " +
                                                " result      ='" + _result.ToString + "'," +
                                                " send_time   ='" + _mt_send_datetime + "', " +
                                                " finish_time ='" + _mt_sent_datetime + "' " +
                          " WHERE                 moseq       ='" + _row("moseq").ToString + "'"

                    rtbLog.AppendText(vbNewLine + """" + _row("msgbody") + """=>" + Format(Date.Now, "yyyy/MM/dd HH:mm:ss"))
                Else
                    sql = " UPDATE tb_mt_hist SET result    ='" + _result.ToString + "', " +
                                                " send_time ='" + _mt_send_datetime + "'" +
                          " WHERE                 moseq     ='" + _row("moseq").ToString + "'"

                    rtbLog.AppendText(vbNewLine + """" + _row("msgbody") + """=>" + Format(Date.Now, "yyyy/MM/dd HH:mm:ss"))
                End If
                sqlcmd.Dispose()
                sqlcmd.Clone()

                sqlcmd = New OracleCommand(sql, oradbConnection)
                sqlcmd.CommandType = CommandType.Text
                sqlcmd.ExecuteNonQuery()
            Next
            sqlcmd.Dispose()
            _dataAdapter.Dispose()
            _dataTable.Dispose()
        Catch ex As Exception
            rtbLog.AppendText(vbNewLine + ex.Message + ", " + Format(Date.Now, "yyyyMMdd HH:mm:ss"))
        End Try
    End Sub
    Private Sub saveLogs()
        Dim _todaylogdir As String = _smsRootdir + smsSettings.logdir
        _todaylogdir = mkDir(_todaylogdir)
        _todaylogdir = _todaylogdir + _today
        _todaylogdir = mkDir(_todaylogdir)

        Dim _logfile As String = _todaylogdir + "_log" + Format(Date.Now, "HHmmss") + ".log"

        If rtbLog.Text <> "" Then rtbLog.SaveFile(_logfile, RichTextBoxStreamType.UnicodePlainText)
        rtbLog.Clear()
    End Sub
#End Region
    
End Class



